package com.kdtech.analyse.video;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.analyse.AnalyseNews;

public class JoyAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {
		boolean bRet = false;
		//http://news.joy.cn/video/4190311.htm
		//http://www.joy.cn/videoSport?resourceId=60225469
		String[] regex = {
				"http://.*.joy.cn/video/[0-9]*.htm",
				"http://.*.joy.cn/.*video.*[?]resourceId=[0-9]+",
				};
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}
	
	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (!isDetailPage(urlMeta.getUrl())) {
		}
		NewsMeta video = new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}		
		String html = urlMeta.getHtml();
		String url = urlMeta.getUrl();		
		video.setUrl(url);		
		String title = null;
		String desc = null;
		Long date = 0l;
		
			
		
		Document doc = Jsoup.parse(html);
		/*
		 * 解析标题
		 */
		title = doc.select("h1").text();
		if(title.startsWith("视频：")){
			title = title.substring("视频：".length());
		}
		
		
		/*
		 * 解析时间
		 */
		String attr = doc.select("video  source").attr("src");
		if(StringUtils.isNotBlank(attr)){
			attr = StringUtils.substringAfterLast(attr, "/");
			attr = StringUtils.substringBefore(attr, "_");
			try {
				date = new Date(Long.parseLong(attr)).getTime();
			} catch (NumberFormatException e) {
			}
		}
		if(date==null){
			String text = doc.select("div.v_title").text();
			date = DateUtils.matchDate(text);
			if(date==null){
				date = DateUtils.matchDate(doc.select("div.guide div.time").text());
			}
		}
		
		
		/*
		 * 解析内容
		 */
		desc = doc.select("div.v_info> div.subinfo> p").text();
		if(StringUtils.isBlank(title)){
		}
		video.setTitle(title);
		video.setDate(date);
		video.setContent(desc);
		
		return video;
	}
	
	public NewsMeta Update(NewsMeta meta) {
	
		return meta;
	}
	
	public static void main(String[] args) {
		JoyAnalyse a = new JoyAnalyse();
		String url = "http://www.joy.cn/news/video?resourceId=60234052";
		if(a.isDetailPage(url)){
			UrlMeta meta = CrawlHTML.responseToURL(url);
			NewsMeta parserHtml = a.parserHtml(meta);
			System.out.println(parserHtml);
		}else{
			System.out.println("不匹配规则");
		}
		
	}

	

	
}
